package cn.usts.edu.lesson07;

/**
 * 编程模型: A,B共有一个账户,俩人一块要取钱,都在手机上操作
 * 账户上有100, A取要90,B要取80;
 * 连个人同时看到都有100.都可以取出,
 * 所以问题就产生了.
 *
 * 解决方案:
 *    锁块,对account上锁,只能一个线程对account操作.[同步块]
 * */

public class UnSafeBank {

    public static void main(String[] args) {
        Account account = new Account(100,"旅游基金");
        Drawing a = new Drawing(account, 90);
        Drawing b = new Drawing(account, 80);
        new Thread(a, "A").start();
        new Thread(b, "B").start();
    }
}

// 账户
class Account {
    int money;
    String name;

    public Account(int money, String name) {
        this.money = money;
        this.name = name;
    }
}

// 银行
class Drawing implements Runnable{

    final Account account;
    int drawMoney;
    int nowMoney=0;


    public Drawing(Account account, int drawMoney) {
        this.account = account;
        this.drawMoney = drawMoney;

    }

    @Override
    public void run() {
        synchronized (account){   // 锁块,对account上锁,只能一个线程对account操作.
            System.out.println(Thread.currentThread().getName()+"要取出"+drawMoney);
            // 判断是否够取出的
            if (account.money-drawMoney<0){
                System.out.println(Thread.currentThread().getName()+"==输入的金额有问题,取不了");
                return;
            }

            // 现在手上的钱
            nowMoney = nowMoney+drawMoney;
            System.out.println(Thread.currentThread().getName()+"现在手上:"+nowMoney);

            // 现在的卡内余额
            account.money=account.money-drawMoney;
            System.out.println(account.name+"余额:"+account.money);
        }


    }
}